import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/config/config.dart';
import 'package:tiktokadult/hj_page/mine_business/ai/ai_sub_type/ai_function_Logic.dart';
import 'package:tiktokadult/hj_page/mine_business/ai/widget/pic_selected_view.dart';
import 'package:tiktokadult/hj_page/pre_sale/pre_sale_provider.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/routers/jump_router.dart';
import 'package:tiktokadult/tools_base/banner/ads_banner_widget.dart';
import 'package:tiktokadult/tools_base/global_store/store.dart';
import 'package:tiktokadult/tools_base/loading/l_error_widget.dart';
import 'package:tiktokadult/tools_base/loading/loading_center_widget.dart';

//ai脱衣
class AIStripSubPage extends StatefulWidget {
  final AIFunctionType type;
  const AIStripSubPage({super.key, this.type = AIFunctionType.autoStrip});

  @override
  State<AIStripSubPage> createState() => _AIStripSubPageState();
}

class _AIStripSubPageState extends State<AIStripSubPage> {
  @override
  Widget build(BuildContext context) {
    return GetBuilder<AIStripLogic>(
      init: instanceController(null, widget.type),
      global: false,
      builder: (logic) {
        if (logic.rawDataModel == null) return LoadingCenterWidget();
        if (logic.rawDataModel!.aiUndressMod?.isEmpty == true) return CErrorWidget();
        return Container(
          padding: EdgeInsets.symmetric(horizontal: 16),
          child: Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      12.sizeBoxH,
                      Row(
                        children: [
                          SizedBox(
                            width: 120,
                            height: 120,
                            child: PicSelectedView(
                              width: 120,
                              height: 120,
                              uploadModel: logic.uploadModel,
                              selectAction: () => logic.update(),
                            ),
                          ),
                          12.sizeBoxW,
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  "注意事项：",
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 14,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                                6.sizeBoxH,
                                Text(
                                  '''1.照片只含有一名人物
2. 图片不能过暗
3. 照片应尽量清晰
4. 不支持多人图片禁止未成年人图片
${widget.type == AIFunctionType.autoStrip ? '5. 上传图片需间隔60s' : '5. 涂抹你想要替换的部分'}''',
                                  style: TextStyle(
                                    color: Color(0xff989898),
                                    fontSize: 12,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                      18.sizeBoxH,
                      0.5.line,
                      18.sizeBoxH,
                      Text(
                        "案例鉴赏",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      12.sizeBoxH,
                      //手动脱衣 && 有涂鸦数据
                      _buildBanner(logic),
                      26.sizeBoxH,
                      Column(
                        children: [
                          Consumer<GlobalStore>(builder: (_, provider, __) {
                            final freeTimes = provider.wallet?.aiUndressFreeTimes ?? 0;
                            final presaleCount = presaleProvider.remain?.todayAiUndressCount ?? 0;
                            //预售权益和免费次数的和
                            final total = freeTimes + presaleCount;
                            final hasFreeTimes = total > 0;
                            return Column(
                              children: [
                                Text(
                                  '你当前免费体验为$total次数',
                                  style: TextStyle(
                                    color: Color(0xff989898),
                                    fontSize: 12,
                                  ),
                                ),
                                12.sizeBoxH,
                                Text(
                                  '当日免费$freeTimes次数',
                                  style: TextStyle(
                                    color: Color(0xff989898),
                                    fontSize: 12,
                                  ),
                                ),
                                12.sizeBoxH,
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                      "处理一张照片的费用是 ",
                                      style: TextStyle(
                                        color: Color(0xff989898),
                                        fontSize: 12,
                                      ),
                                    ),
                                    Text(
                                      "${(Config.aiUndressPrice ?? 0)}金币",
                                      style: TextStyle(
                                        color: AppColors.actionRed,
                                        fontSize: 12,
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            );
                          }),
                          9.sizeBoxH,
                          82.sizeBoxH,
                          20.sizeBoxH,
                        ],
                      ),
                    ],
                  ),
                ),
              ),
              _buildBtn(logic),
              6.sizeBoxH,
            ],
          ),
        );
      },
    );
  }

  _buildBanner(AIStripLogic _) {
    Widget? content;
    //1.智能脱衣
    if (widget.type == AIFunctionType.autoStrip) {
      content = AdsBannerWidget(
        _.rawDataModel?.aiUndressMod ?? [],
        isIndicatorBottomCenter: true,
        onItemClick: (index) {
          final ad = (_.rawDataModel!.aiUndressMod ?? [])[index];
          pushToPageByLink(ad.href, id: ad.id);
        },
      );
    } else {
      //2.手动脱衣, 无上传
      if (_.uploadModel.localPicList.isEmpty) {
        content = Image.asset('ai_auto_cover.gif'.aiPath);
      } else {
        //有涂鸦
        if (_.uploadModel.graffitiModel?.showGraffitiData != null) {
          content = Row(
            children: [
              Expanded(
                child: Image.file(
                  File(_.uploadModel.localPicList[0]),
                ),
              ),
              Expanded(
                  child: Image.memory(
                _.uploadModel.graffitiModel!.showGraffitiData!,
              ))
            ],
          );
        } else {
          //无涂鸦
          content = Image.file(
            File(_.uploadModel.localPicList[0]),
          );
        }
      }
    }
    return AspectRatio(aspectRatio: _.aspectRatio, child: content);
  }

  _buildBtn(AIStripLogic _) {
    //1.智能脱衣
    if (widget.type == AIFunctionType.autoStrip) {
      return _buildBtnStyle("提交", () => _.submitAiImage()).paddingSymmetric(
        horizontal: 30,
      );
    } else {
      //2.手动脱衣, 无上传
      if (_.uploadModel.localPicList.isEmpty) {
        return _buildBtnStyle("提交", () => _.submitAiImage()).marginSymmetric(
          horizontal: 30,
        );
      } else {
        //有涂鸦
        if (_.uploadModel.graffitiModel?.showGraffitiData != null) {
          return Row(
            children: [
              Expanded(flex: 1, child: _buildRebuildBtn(_)),
              10.sizeBoxW,
              Expanded(
                flex: 2,
                child: _buildBtnStyle(
                  "提交",
                  () => _.submitAiImage(),
                ),
              )
            ],
          );
        } else {
          //无涂鸦
          return Container();
        }
      }
    }
  }

  _buildRebuildBtn(AIStripLogic _) {
    return Container();
    // return GestureDetector(
    //   onTap: () => _.gotoAiGrafftiPage(),
    //   child: Container(
    //     height: 44,
    //     alignment: Alignment.center,
    //     decoration: BoxDecoration(
    //       color: Colors.white.withOpacity(.1),
    //       borderRadius: BorderRadius.circular(4),
    //     ),
    //     child: Text(
    //       '重新涂抹',
    //       style: TextStyle(
    //         color: Colors.white.withOpacity(.7),
    //         fontSize: 16,
    //         fontWeight: FontWeight.w500,
    //       ),
    //     ),
    //   ),
    // );
  }

  Widget _buildBtnStyle(String title, Function()? action) {
    return GestureDetector(
      onTap: () => action?.call(),
      child: Container(
        height: 44,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: AppColors.actionRed,
          borderRadius: BorderRadius.circular(3),
        ),
        child: Text(
          title,
          style: TextStyle(
            color: Colors.white,
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }
}
